package com.example.pt.controller;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.enums.Category;
import com.example.pt.service.*;
import com.example.pt.entity.*;
import com.example.pt.service.impl.PromotionServiceImpl;
import com.example.pt.utils.Result;
import com.example.pt.util.BencodingUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.ErrorManager;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import com.example.pt.utils.*;
import org.springframework.web.multipart.MultipartFile;
//import java.util.Optional;

@RestController
@RequestMapping("/torrentfiles")
@CrossOrigin(origins = "*")
public class TorrentFileController {

    private static final Logger log = LoggerFactory.getLogger(TorrentFileController.class);


    @Autowired
    private TorrentFileService torrentFileService;

    @Autowired
    private RecommendationService recommendationService;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private TorrentInfoHashService torrentInfoHashService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;

    @Autowired
    private TorrentSeedStatsService torrentSeedStatsService;

    //上传文件的文件地址
    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH = "E:\\PrivateTracker\\file";
    
    // Tracker URL - 使用新的无线局域网适配器WLAN的IP
    private static final String TRACKER_URL = "http://172.20.10.11:6969/announce";

    @GetMapping
    public ResponseEntity<?> getAllTorrentFiles() {
        List<TorrentFile> files = torrentFileService.getAllTorrentFiles();
        
        // 将每个种子文件的category从int转换为对应的字符串名称
        List<Map<String, Object>> result = files.stream().map(file -> {
            Map<String, Object> fileMap = new HashMap<>();
            fileMap.put("tid", file.getTid());
            fileMap.put("uid", file.getUid());
            fileMap.put("title", file.getTitle());
            fileMap.put("fileUrl", file.getFileUrl());
            fileMap.put("category", Category.getNameByValue(file.getCategory()));
            fileMap.put("format", file.getFormat());
            fileMap.put("language", file.getLanguage());
            fileMap.put("description", file.getDescription());
            fileMap.put("fileSize", file.getFileSize());
            fileMap.put("uploadTime", file.getUploadTime());
            fileMap.put("status", file.getStatus());
            fileMap.put("downloadCount", file.getDownloadCount());
            fileMap.put("viewCount", file.getViewCount());
            fileMap.put("seederCount", file.getSeederCount());
            return fileMap;
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(result);
    }

    /**
     *
     * @param header 请求头
     * @return
     */

    @GetMapping("/getTorrent")
    public ResponseEntity<?> getTorrentFileByUid(@RequestHeader Map<String, String> header) {
        Map<String, Object> response = new HashMap<>();

        // 检查请求头中是否包含token
        String token = header.get("token");
        if (token == null || token.isEmpty()) {
            response.put("error", "缺少token请求头");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        DecodedJWT decode;
        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {
            response.put("token", "登录权限已失效！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        // 检查token中是否包含uid声明
        Claim uidClaim = decode.getClaim("uid");
        if (uidClaim.isNull()) {
            response.put("error", "无效的用户标识");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        int userId = uidClaim.asInt();
        Object fileResult = getTorrentFilesByUser(userId);

        // 处理返回值是ResponseEntity的情况
        if (fileResult instanceof ResponseEntity) {
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) fileResult;
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                Object body = responseEntity.getBody();
                if (body instanceof List<?>) {
                    @SuppressWarnings("unchecked")
                    List<TorrentFile> torrentFiles = (List<TorrentFile>) body;
                    return processTorrentFiles(torrentFiles);
                } else {
                    response.put("error", "服务返回格式错误");
                    return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
                }
            } else {
                return responseEntity; // 直接返回原响应
            }
        }

        // 处理返回值是List<TorrentFile>的情况（原有逻辑）
        if (fileResult == null) {
            response.put("message", "获取文件列表失败");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        if (!(fileResult instanceof List<?>)) {
            response.put("error", "服务返回格式错误");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        @SuppressWarnings("unchecked")
        List<TorrentFile> torrentFiles = (List<TorrentFile>) fileResult;

        return processTorrentFiles(torrentFiles);
    }

    @GetMapping("/getTorrentUID/{uid}")
    public ResponseEntity<?> getTorrentFileByUid(@RequestHeader Map<String, String> header,@PathVariable int uid) {
        Map<String, Object> response = new HashMap<>();

        // 检查请求头中是否包含token
        String token = header.get("token");
        if (token == null || token.isEmpty()) {
            response.put("error", "缺少token请求头");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        DecodedJWT decode;
        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {
            response.put("token", "登录权限已失效！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }
//
//        // 检查token中是否包含uid声明
//        Claim uidClaim = decode.getClaim("uid");
//        if (uidClaim.isNull()) {
//            response.put("error", "无效的用户标识");
//            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
//        }
//
//        int userId = uidClaim.asInt();
        int userId = uid;
        Object fileResult = getTorrentFilesByUser(userId);

        // 处理返回值是ResponseEntity的情况
        if (fileResult instanceof ResponseEntity) {
            ResponseEntity<?> responseEntity = (ResponseEntity<?>) fileResult;
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                Object body = responseEntity.getBody();
                if (body instanceof List<?>) {
                    @SuppressWarnings("unchecked")
                    List<TorrentFile> torrentFiles = (List<TorrentFile>) body;
                    return processTorrentFiles(torrentFiles);
                } else {
                    response.put("error", "服务返回格式错误");
                    return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
                }
            } else {
                return responseEntity; // 直接返回原响应
            }
        }

        // 处理返回值是List<TorrentFile>的情况（原有逻辑）
        if (fileResult == null) {
            response.put("message", "获取文件列表失败");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        if (!(fileResult instanceof List<?>)) {
            response.put("error", "服务返回格式错误");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        @SuppressWarnings("unchecked")
        List<TorrentFile> torrentFiles = (List<TorrentFile>) fileResult;

        return processTorrentFiles(torrentFiles);
    }

    private ResponseEntity<?> processTorrentFiles(List<TorrentFile> torrentFiles) {
        if (torrentFiles.isEmpty()) {
            return ResponseEntity.ok(Collections.emptyList());
        }

        List<Map<String, Object>> result = new ArrayList<>();

        for (TorrentFile file : torrentFiles) {
            if (file == null) continue; // 跳过空文件对象

            Map<String, Object> data = new HashMap<>();
            data.put("tid", file.getTid());
            data.put("fileName",file.getTitle());
            data.put("fileSize", file.getFileSize());
            data.put("uploadTime", file.getUploadTime());
            data.put("downloadCount", file.getDownloadCount());
            data.put("category", Category.getNameByValue(file.getCategory()));
            data.put("viewCount", file.getViewCount());
            data.put("status", file.getStatus());
            data.put("title", file.getTitle() != null ? file.getTitle() : "");
            data.put("description", file.getDescription() != null ? file.getDescription() : "");
            data.put("format", file.getFormat() != null ? file.getFormat() : "");
            data.put("language", file.getLanguage() != null ? file.getLanguage() : "");

            result.add(data);
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/{tid}")
    public ResponseEntity<?> getTorrentFileById(@PathVariable int tid, @RequestHeader Map<String, String> header) {
        try {
            System.out.println("开始处理种子详情请求: tid=" + tid);
            Optional<TorrentFile> fileOpt = torrentFileService.getTorrentFileByTid(tid);
            
            if (!fileOpt.isPresent()) {
                log.warn("请求不存在的种子: tid={}", tid);
                System.out.println("种子不存在: tid=" + tid);
                return new ResponseEntity<>(Result.fail("种子不存在"), HttpStatus.NOT_FOUND);
            }
            
            TorrentFile file = fileOpt.get();
            log.debug("获取种子详情: tid={}, 标题={}", tid, file.getTitle());
            System.out.println("成功获取种子详情: tid=" + tid + ", 标题=" + file.getTitle());

            // 记录用户点击行为（如果有用户登录）
            // 从请求头中获取token
            String token = null;
            
            // 打印所有请求头，用于调试
            System.out.println("所有请求头:");
            header.forEach((key, value) -> System.out.println(key + ": " + value));
            
            // 如果没有找到token头，尝试从Authorization头获取
            if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
                String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
                // 检查是否包含Bearer前缀
                if (authHeader != null && !authHeader.isEmpty()) {
                    if (authHeader.startsWith("Bearer ")) {
                        token = authHeader.substring(7); // 移除"Bearer "前缀
                    } else {
                        token = authHeader;
                    }
                    log.debug("从Authorization头提取token: {}", token);
                    System.out.println("从Authorization头提取token: " + token);
                }
            }
            
            // 如果Authorization头没有找到token，再尝试从自定义token头获取
            if ((token == null || token.isEmpty()) && header.containsKey("token")) {
                token = header.get("token");
                log.debug("从token头提取token成功: {}", token);
                System.out.println("从token头提取token成功: " + token);
            }
            
            Integer uid = 0; // 默认匿名用户
            
            if (token != null && !token.isEmpty()) {
                try {
                    log.debug("开始验证token...");
                    System.out.println("开始验证token: " + token);
                    DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                    
                    if (decodedJWT != null) {
                        try {
                            uid = decodedJWT.getClaim("uid").asInt();
                            log.info("token验证成功，用户ID: {}", uid);
                            System.out.println("token验证成功，用户ID: " + uid);
                            
                            // 记录用户点击
                            log.info("开始记录用户点击行为: uid={}, tid={}", uid, tid);
                            System.out.println("开始记录用户点击行为: uid=" + uid + ", tid=" + tid);
                            recommendationService.recordUserClick(uid, tid);
                            log.info("用户点击行为记录成功");
                            System.out.println("用户点击行为记录成功");
                        } catch (Exception e) {
                            log.warn("从token中提取uid失败: {}", e.getMessage());
                            System.out.println("从token中提取uid失败: " + e.getMessage());
                            e.printStackTrace();
                        }
                    } else {
                        log.warn("token验证返回null");
                        System.out.println("token验证返回null");
                    }
                } catch (Exception e) {
                    // token验证失败，不记录点击行为
                    log.warn("token验证失败，不记录用户点击: {}", e.getMessage());
                    System.out.println("token验证失败，不记录用户点击: " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                log.debug("未提供有效token，匿名用户访问种子，不记录点击历史");
                System.out.println("未提供有效token，匿名用户访问种子，不记录点击历史");
            }
            
            // 增加浏览次数
            torrentFileService.incrementViewCount(tid);
            log.debug("增加种子浏览次数: tid={}, 当前浏览量={}", tid, file.getViewCount() + 1);
            System.out.println("增加种子浏览次数: tid=" + tid + ", 当前浏览量=" + (file.getViewCount() + 1));
            Map promotion = promotionService.getMaxDiscountInfo(tid);
            
            Map<String, Object> data = new HashMap<>();
            data.put("tid", file.getTid());
            data.put("fileName", file.getFileUrl());
            data.put("fileSize", file.getFileSize());
            data.put("uploadTime", file.getUploadTime());
            data.put("downloadCount", file.getDownloadCount());
            data.put("category", Category.getNameByValue(file.getCategory()));
            data.put("viewCount", file.getViewCount());
            data.put("status", file.getStatus());
            data.put("title", file.getTitle());
            data.put("description", file.getDescription());
            data.put("format", file.getFormat());
            data.put("language", file.getLanguage());
            data.put("promotionName",promotion.get("discountName"));
            data.put("promotionStart",promotion.get("startTime"));
            data.put("promotionEnd",promotion.get("endTime"));

            if(favoriteService.isFavorited(uid,tid)){
                data.put("favorited", true);
            }else{
                data.put("favorited", false);
            }


            return ResponseEntity.ok(Result.success(data, "得到种子文件详细信息"));
        } catch (Exception e) {
            log.error("获取种子详情失败: {}", e.getMessage(), e);
            System.out.println("获取种子详情失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.ok(Result.fail("获取种子详情失败: " + e.getMessage()));
        }
    }

    @GetMapping("/user/{uid}")
    public ResponseEntity<List<TorrentFile>> getTorrentFilesByUser(@PathVariable int uid) {
        List<TorrentFile> files = torrentFileService.getTorrentFilesByUser(uid);
        return new ResponseEntity<>(files, HttpStatus.OK);
    }

    @GetMapping("/category/{category}")
    public ResponseEntity<List<TorrentFile>> getTorrentFilesByCategory(@PathVariable int category) {
        List<TorrentFile> files = torrentFileService.getTorrentFilesByCategory(category);
        return new ResponseEntity<>(files, HttpStatus.OK);
    }

    //根据种子状态返回种子
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getTorrentFilesByStatus(@PathVariable int status,@RequestHeader Map<String, String> header) {
        String token =  header.get("token");
        DecodedJWT decode;
        Map<String, Object> response = new HashMap<>();

        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {

            response.put("token", "登录权限已失效！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }
        int usertype = decode.getClaim("usertype").asInt();
        // 检查权限
        if (usertype == 1) {
            System.out.println(usertype);
            response.put("success", false);
            response.put("message", "没有权限审核");
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
        }
        List<TorrentFile> files = torrentFileService.getTorrentFilesByStatus(status);
        List<Map<String, Object>> result = new ArrayList<>();

        for (TorrentFile file : files) {
            Map<String, Object> data = new HashMap<>();
            data.put("tid", file.getTid());
            data.put("fileName", file.getFileUrl()); // 假设应该使用fileName
            data.put("fileSize", file.getFileSize());
            data.put("uploadTime", file.getUploadTime());
            data.put("downloadCount", file.getDownloadCount());

            String categoryName = Category.getNameByValue(file.getCategory());
            data.put("category", categoryName != null ? categoryName : "未知分类");

            data.put("viewCount", file.getViewCount());
            data.put("status", file.getStatus());
            data.put("title", file.getTitle());
            data.put("description", file.getDescription());
            data.put("format", file.getFormat());
            data.put("language", file.getLanguage());

            result.add(data);
        }
        return ResponseEntity.ok(Result.success(result, "得到种子文件详细信息"));

    }

    @GetMapping("/search")
    public ResponseEntity<List<TorrentFile>> searchTorrentFiles(@RequestParam String keyword) {
        List<TorrentFile> files = torrentFileService.searchTorrentFiles(keyword);
        return new ResponseEntity<>(files, HttpStatus.OK);
    }

    /**
     * 上传种子
     * @param header
     * @param title
     * @param category
     * @param format
     * @param language
     * @param description
     * @param file
     * @return
     */

    @PostMapping("/upload")
    public ResponseEntity<?> uploadTorrentFile(
            @RequestHeader Map<String, String> header,
            @RequestParam("title") String title,
            @RequestParam("category") String category,
            @RequestParam("format") String format,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam("description") String description,
            @RequestPart("file") MultipartFile file) {

        String originalname = file.getOriginalFilename();
        System.out.println(originalname);
        if (originalname == null) {
            return ResponseEntity.ok(Result.fail("文件名为空，无法识别格式"));
        }
        boolean isTorrent = originalname.toLowerCase().endsWith(".torrent");
//        boolean isTorrentZip = originalname.toLowerCase().endsWith(".torrent.zip");
        if (!isTorrent ) {
            return ResponseEntity.ok(Result.fail("文件格式错误，仅支持.torrent或.torrent.zip"));
        }

        // 校验文件大小（10MB ≤ size < 50GB）
        long fileSize = file.getSize();
        long minSize = 1 * 1024; // 1KB
        long maxSize = 50L * 1024 * 1024 * 1024; // 50GB
//        System.out.println(fileSize);
        // 修正判断条件：确保文件大小在 [1KB, 50GB) 范围内
//        if (fileSize < minSize || fileSize >= maxSize) {
//            System.out.println(minSize);
//            System.out.println(maxSize);
//            System.out.println(fileSize);
//            // 错误信息与实际校验逻辑保持一致
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("文件大小必须大于1KB小于50G");
//        }

        if (isTorrent) {
            try {
                // 读取文件前1024字节验证头部特征
                byte[] headerBytes = new byte[1024];
                int bytesRead = file.getInputStream().read(headerBytes);
                String headerStr = new String(headerBytes, 0, bytesRead);

                // 检查是否包含必选字段标识（简化版：校验Bencode字典起始和字段关键字）
                if (!headerStr.startsWith("d")) {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("文件非有效种子文件，不是字典格式");
                }
                // 仅检查文件是否以'd'开头，表示是Bencode字典格式
                // 不再严格要求必须包含announce和info字段
            } catch (IOException e) {
                log.error("种子文件头部验证失败: {}", e.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("种子文件头部验证失败");
            }
        }


        DecodedJWT decodedJWT = null;
        // 验证Token
        String token = header.get("token"); // 自定义token头

        // 如果没有找到token头，尝试从Authorization头获取
        if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
            String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
            // 检查是否包含Bearer前缀
            if (authHeader != null && !authHeader.isEmpty()) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7); // 移除"Bearer "前缀
                } else {
                    token = authHeader;
                }
                log.debug("从Authorization头提取token: {}", token);
                System.out.println("从Authorization头提取token: " + token);
            }
        }

        try {
            decodedJWT = JWTUtil.verifyToken(token);
            if (decodedJWT == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("token", "登录权限已失效！");
                return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("token", "登录权限已失效！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        try {
            // 获取用户ID
            int uid = decodedJWT.getClaim("uid").asInt();

            // 保存上传的文件到临时文件
            Path tempInputFile = Files.createTempFile("upload_", ".torrent");
            file.transferTo(tempInputFile.toFile());

            log.info("已保存上传的种子文件到临时目录: {}, 大小: {} 字节",
                tempInputFile, Files.size(tempInputFile));

            // 创建最终保存的文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "unknown.torrent";
            }

            if (!originalFilename.toLowerCase().endsWith(".torrent")) {
                originalFilename += ".torrent";
            }

            // 确保ROOT_PATH目录存在
            if (!FileUtil.exist(ROOT_PATH)) {
                FileUtil.mkdir(ROOT_PATH);
            }

            // 处理种子文件 - 设置tracker URL并添加用户ID作为passkey
            File outputFile = new File(ROOT_PATH, originalFilename);

            // 如果文件已存在，则重命名
            if (outputFile.exists()) {
                String filenameWithoutExt = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
                String ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
                originalFilename = filenameWithoutExt + "_" + System.currentTimeMillis() + ext;
                outputFile = new File(ROOT_PATH, originalFilename);
            }

            // 使用BencodingUtils设置tracker URL和passkey
            boolean success = BencodingUtils.setTrackerUrl(
                tempInputFile.toFile(), outputFile, TRACKER_URL, String.valueOf(uid));

            if (!success) {
                log.error("处理种子文件失败");
                return ResponseEntity.ok(Result.fail("处理种子文件失败，无法设置tracker URL"));
            }

            log.info("已为上传者(UID:{})设置tracker URL: {}，并添加passkey: {}",
                uid, TRACKER_URL, uid);

            // 获取种子文件中描述的实际内容大小，而不是种子文件自身的大小
            fileSize = BencodingUtils.getTotalContentSize(outputFile);

            // 保存到数据库
            TorrentFile savedFile = torrentFileService.uploadTorrentFile(
                    ROOT_PATH + "\\" +originalFilename, uid, title, Category.getValueByName(category), format, language, description, fileSize);

            // 获取InfoHash并保存映射关系
            String infoHash = BencodingUtils.getInfoHash(outputFile);
            if (infoHash != null && !infoHash.isEmpty()) {
                torrentInfoHashService.saveMapping(savedFile.getTid(), infoHash);
                log.info("已保存种子ID与InfoHash映射关系: tid={}, infoHash={}", savedFile.getTid(), infoHash);
            } else {
                log.warn("无法获取种子文件的InfoHash: tid={}, file={}", savedFile.getTid(), outputFile.getAbsolutePath());
            }

            // 返回成功信息
            Map<String, Object> data = new HashMap<>();
            data.put("tid", savedFile.getTid());
            data.put("fileName", savedFile.getFileUrl());
            data.put("fileSize", fileSize);
            data.put("uploadTime", savedFile.getUploadTime());
            data.put("downloadUrl", "/torrentfiles/download/" + savedFile.getTid());

            return ResponseEntity.ok(Result.success(data, "种子文件上传成功，已设置tracker URL和passkey"));

        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("文件上传失败" + e.getMessage());
        }
    }

    @PutMapping("/update/{tid}")
    public ResponseEntity<?> editTorrentFile(
            @RequestHeader Map<String, String> header,
            @PathVariable int tid,
            @RequestParam("title") String title,
            @RequestParam("category") String category,
            @RequestParam("format") String format,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam("description") String description,
            @RequestPart(value = "file", required = false) MultipartFile file) {

        DecodedJWT decodedJWT;
        String token = header.get("token");
        
        // 如果没有找到token头，尝试从Authorization头获取
        if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
            String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
            // 检查是否包含Bearer前缀
            if (authHeader != null && !authHeader.isEmpty()) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7); // 移除"Bearer "前缀
                } else {
                    token = authHeader;
                }
                log.debug("从Authorization头提取token: {}", token);
                System.out.println("从Authorization头提取token: " + token);
            }
        }

        try {
            decodedJWT = JWTUtil.verifyToken(token);
            int uid = decodedJWT.getClaim("uid").asInt();
            String savedFileName = null;
            long fileSize = 0;

            Optional<TorrentFile> optionalTorrentFile = torrentFileService.getTorrentFileByTid(tid);

            if (!optionalTorrentFile.isPresent()) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "文件不存在");
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }

            TorrentFile existingTorrentFile = optionalTorrentFile.get();
            if (existingTorrentFile == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "文件不存在");
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }

            // 判断当前用户的uid是否与要更新的TorrentFile的uid一致
            if (existingTorrentFile.getUid() != uid) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "没有权限修改此文件");
                return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
            }

            // 如果有新文件上传，则更新文件内容
            if (file != null && !file.isEmpty()) {
                savedFileName = uploadFile(file);
                // 获取种子文件中描述的实际内容大小，而不是种子文件自身的大小
                File torrentFile = new File(ROOT_PATH, savedFileName);
                fileSize = BencodingUtils.getTotalContentSize(torrentFile);
                
                // 如果更新了种子文件，重新获取并更新InfoHash
                String infoHash = BencodingUtils.getInfoHash(torrentFile);
                if (infoHash != null && !infoHash.isEmpty()) {
                    torrentInfoHashService.saveMapping(tid, infoHash);
                    log.info("已更新种子ID与InfoHash映射关系: tid={}, infoHash={}", tid, infoHash);
                } else {
                    log.warn("无法获取更新后种子文件的InfoHash: tid={}, file={}", tid, torrentFile.getAbsolutePath());
                }
            }
            int status = 0;

            TorrentFile updatedFile = torrentFileService.updateTorrentFile(
                    tid, uid, title, Category.getValueByName(category), format, language, description, savedFileName, fileSize,status);

            Map<String, Object> response = new HashMap<>();
            response.put("修改结果", "文件信息修改成功: " + updatedFile.getFileUrl());
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (IOException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "文件上传失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "修改失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
    }

    //1是普通用户 0是管理员
    // 0: 待审核, 1: 审核通过, 2: 审核拒绝
    @PutMapping("/{tid}/updateStatus/{status}")
    public ResponseEntity<Map<String, Object>> updateStatus(@RequestHeader Map<String, String> headers,
                                                            @PathVariable int tid,
                                                            @PathVariable int status) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 从请求头中获取token
            String token = headers.get("token");

            // 如果没有找到token头，尝试从Authorization头获取
            if ((token == null || token.isEmpty()) && (headers.containsKey("authorization") || headers.containsKey("Authorization"))) {
                String authHeader = headers.getOrDefault("authorization", headers.getOrDefault("Authorization", ""));
                // 检查是否包含Bearer前缀
                if (authHeader != null && !authHeader.isEmpty()) {
                    if (authHeader.startsWith("Bearer ")) {
                        token = authHeader.substring(7); // 移除"Bearer "前缀
                    } else {
                        token = authHeader;
                    }
                    System.out.println("从Authorization头提取token: " + token);
                }
            }

            // 验证token存在性
            if (token == null || token.isEmpty()) {
                response.put("success", false);
                response.put("message", "缺少token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 验证token有效性
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);

            // 获取用户权限类型
            int usertype = decodedJWT.getClaim("usertype").asInt();

            // 检查权限
            if (usertype == 1) {
                System.out.println(usertype);
                response.put("success", false);
                response.put("message", "没有权限审核");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }

            // 验证status参数 (只能是1或2)
            if (status != 1 && status != 2) {
                response.put("success", false);
                response.put("message", "无效的状态值。status只能是1(审核通过)或2(审核拒绝)");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            // 更新文件状态
            TorrentFile updatedFile = torrentFileService.updateStatus(tid, status);

            // 检查文件是否存在
            if (updatedFile == null) {
                response.put("success", false);
                response.put("message", "文件不存在或更新失败");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 更新成功
            response.put("success", true);
            response.put("message", status == 1 ? "审核通过" : "审核拒绝");
            response.put("data", updatedFile);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            // 处理其他异常
            log.error("更新文件状态时发生错误", e);
            response.put("success", false);
            response.put("message", "更新状态失败，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }



    public String uploadFile(MultipartFile file) throws IOException {
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);  // 如果当前文件的父级目录不存在，就创建
        }

        String originalFilename = file.getOriginalFilename();  // 文件的原始名称
        String extName = FileUtil.extName(originalFilename); // 获取文件扩展名
        System.out.println("文件的原始名称：" + originalFilename);

        // 检查文件是否存在并处理重命名
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            // 如果当前上传的文件已经存在了，那么这个时候就要重命名一个文件名称
            originalFilename = torrentFileService.getAllTorrentFiles().size() + 1 + "." + extName;
        }

        // 保存文件到本地
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        System.out.println("文件的保存路径：" + saveFile.getAbsolutePath());
        file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去

        // 返回保存的文件名
        return originalFilename;
    }



    /**
     * 通过链接下载种子文件（支持从URL参数获取token）
     */
    @GetMapping("/download/{tid}")
    public ResponseEntity<?> downloadTorrentFile(
            @PathVariable("tid") int tid,
            @RequestHeader Map<String, String> header) {

        // 验证Token
        String token = header.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("status", "fail", "message", "缺少认证信息"));
        }

        try {
            // 验证Token有效性
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            if (decodedJWT == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Map.of("status", "fail", "message", "无效的认证信息"));
            }
            
            // 获取用户ID，用于设置passkey
            int uid = decodedJWT.getClaim("uid").asInt();

            // 获取种子文件路径
            Optional<TorrentFile> optionalFile = torrentFileService.getTorrentFileByTid(tid);
            if (!optionalFile.isPresent()) {
                return ResponseEntity.ok(Map.of(
                        "status", "fail",
                        "message", "找不到指定ID的种子文件"
                ));
            }

            TorrentFile torrentFile = optionalFile.get();
            String fileName = torrentFile.getFileUrl();
            
            // 源文件路径
            File sourceFile = new File(fileName);
            System.out.println("源文件完整路径: " + ROOT_PATH + File.separator + fileName);
            if (!sourceFile.exists()) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("status", "fail", "message", "种子文件不存在于服务器"));
            }
            
            // 创建临时文件，用于替换passkey，但保持原始文件名
            String originalFilename = sourceFile.getName();
            
            // 在临时目录创建一个与原始文件同名的文件夹
            Path tempDir = Files.createTempDirectory("torrent_download_");
            Path tempOutputPath = Paths.get(tempDir.toString(), originalFilename);
            
            // 使用BencodingUtils修改种子文件，替换passkey为下载用户的ID
            boolean success = BencodingUtils.updatePasskey(
                sourceFile, tempOutputPath.toFile(), String.valueOf(uid));
            
            if (!success) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("status", "fail", "message", "处理种子文件失败，无法设置passkey"));
            }
            
            log.info("已为下载者(UID:{})更新passkey，种子文件已保存: {}", 
                uid, tempOutputPath);

            torrentFileService.incrementDownloadCount(tid);

            String torrentPath = tempOutputPath.toString();
            String downloadLink = downloadUrlUtils.generateTorrentDownloadLink(torrentPath);

            if (downloadLink == null) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("status", "fail", "message", "生成下载链接失败"));
            }

            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "downloadLink", downloadLink
            ));

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("status", "fail", "message", e.getMessage()));
        }
    }


 /*
    @GetMapping("/download/{tid}")
    public ResponseEntity<?> downloadTorrentFile(
            @PathVariable("tid") int tid,
            @RequestHeader Map<String, String> header,
            HttpServletResponse response) {

        DecodedJWT decodedJWT;
        // 验证Token
        String token = header.get("token");
        
        // 如果没有找到token头，尝试从Authorization头获取
        if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
            String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
            // 检查是否包含Bearer前缀
            if (authHeader != null && !authHeader.isEmpty()) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7); // 移除"Bearer "前缀
                } else {
                    token = authHeader;
                }
                log.debug("从Authorization头提取token: {}", token);
                System.out.println("从Authorization头提取token: " + token);
            }
        }
        
        try {
            decodedJWT = JWTUtil.verifyToken(token);
            // 检查decodedJWT是否为null
            if (decodedJWT == null) {
                log.error("Token验证失败：decodedJWT为null");
                return ResponseEntity.ok(Result.fail("身份验证失败"));
            }
            
            // 获取用户ID
            int uid = decodedJWT.getClaim("uid").asInt();
            
            // 根据ID获取种子文件
            Optional<TorrentFile> optionalFile = torrentFileService.getTorrentFileByTid(tid);
            
            if (!optionalFile.isPresent()) {
                return ResponseEntity.ok(Result.fail("找不到指定ID的种子文件"));
            }
            
            TorrentFile torrentFile = optionalFile.get();
//            torrentFile.setDownloadCount(torrentFile.getDownloadCount()+1);
            String fileName = torrentFile.getFileUrl();
            
            // 源文件路径
            File sourceFile = new File(ROOT_PATH + File.separator + fileName);
            if (!sourceFile.exists()) {
                return ResponseEntity.ok(Result.fail("种子文件不存在于服务器"));
            }
            
            // 创建临时文件，用于替换passkey
            String originalFilename = sourceFile.getName();
            String filenameWithoutExt = originalFilename;
            String ext = ".torrent";
            
            if (originalFilename.contains(".")) {
                filenameWithoutExt = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
                ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
            }
            
            // 不再修改文件名，保持原始文件名
            String outputFilename = originalFilename;
            Path tempOutputPath = Files.createTempFile("download_", ext);
            
            // 使用BencodingUtils修改种子文件，替换passkey为下载用户的ID
            boolean success = BencodingUtils.updatePasskey(
                sourceFile, tempOutputPath.toFile(), String.valueOf(uid));
            
            if (!success) {
                log.error("处理下载种子文件失败");
                return ResponseEntity.ok(Result.fail("处理种子文件失败，无法设置passkey"));
            }
            
            log.info("已为下载者(UID:{})更新passkey，种子文件已保存: {}", 
                uid, tempOutputPath);
            
            // 增加下载计数
            torrentFileService.incrementDownloadCount(tid);
            
            // 设置响应头，使浏览器下载文件
            response.setContentType("application/x-bittorrent");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + 
                    URLEncoder.encode(outputFilename, StandardCharsets.UTF_8.toString()) + "\"");
            
            // 将文件写入响应流
            try (FileInputStream fis = new FileInputStream(tempOutputPath.toFile());
                 ServletOutputStream sos = response.getOutputStream()) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                
                while ((bytesRead = fis.read(buffer)) != -1) {
                    sos.write(buffer, 0, bytesRead);
                }
                
                sos.flush();
                
                log.info("用户{}成功下载种子文件ID: {}, 已替换passkey", uid, tid);
                
                // 文件已经直接写入响应流，不需要返回内容
                return null;
            }
            
        } catch (NumberFormatException e) {
            return ResponseEntity.ok(Result.fail("无效的ID格式"));
        } catch (IOException e) {
            log.error("文件下载失败: {}", e.getMessage());
            return ResponseEntity.ok(Result.fail("文件下载失败: " + e.getMessage()));
        }
    }*/

    /**
     * 获取推荐种子列表（不分页，返回所有推荐种子和总数）
     * @param header 请求头（包含token）
     * @return 推荐种子列表
     */
    @GetMapping("/recommend")
    public ResponseEntity<Result<Map<String, Object>>> getRecommendedTorrents(@RequestHeader Map<String, String> header) {
        try {
            int uid = 0; // 默认为匿名用户
            
            // 验证Token获取用户ID
            // 尝试从两种可能的请求头中获取token
            String token = header.get("token"); // 自定义token头
            
            // 如果没有找到token头，尝试从Authorization头获取
            if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
                String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
                // 检查是否包含Bearer前缀
                if (authHeader != null && !authHeader.isEmpty()) {
                    if (authHeader.startsWith("Bearer ")) {
                        token = authHeader.substring(7); // 移除"Bearer "前缀
                    } else {
                        token = authHeader;
                    }
                    System.out.println("从Authorization头提取token: " + token);
                }
            }
            
            if (token != null && !token.isEmpty()) {
                try {
                    DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                    uid = decodedJWT.getClaim("uid").asInt();
                    log.info("验证用户成功，用户ID: {}", uid);
                } catch (Exception e) {
                    // token无效或过期，使用默认匿名用户
                    log.warn("Token验证失败: {}, 将使用匿名用户推荐", e.getMessage());
                }
            } else {
                log.info("请求未包含token，将使用匿名用户推荐");
            }
            
            // 获取推荐种子列表（不分页，返回全部）
            log.info("开始为用户ID {} 获取推荐种子（不分页）", uid);
            Map<String, Object> recommendationResult = recommendationService.getRecommendedTorrentsWithBatchId(uid);
            
            // 构建响应
            log.info("成功获取推荐种子返回给用户 {}", uid);
            return new ResponseEntity<>(Result.success(recommendationResult, "获取推荐种子成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取推荐种子时发生错误: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("获取推荐种子失败: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 获取热门种子列表
     * @param pageSize 每页数量
     * @param pageNum 页码（从1开始）
     * @return 热门种子列表
     */
    @GetMapping("/hot")
    public ResponseEntity<Result<Map<String, Object>>> getHotTorrents(
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageNum) {
        try {
            if (pageSize <= 0) {
                pageSize = 10; // 默认返回10个热门种子
            }
            
            if (pageNum < 1) {
                pageNum = 1; // 确保页码至少为1
            }
            
            log.info("请求获取热门种子，每页数量: {}, 页码: {}", pageSize, pageNum);
            
            // 获取热门种子并应用分页
            Map<String, Object> hotTorrentsResult = recommendationService.getHotTorrentsWithBatchId(pageSize * 3);
            
            // 获取种子列表和批次ID
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> allTorrents = (List<Map<String, Object>>) hotTorrentsResult.get("torrents");
            String batchId = (String) hotTorrentsResult.get("batchId");
            
            // 应用分页
            int startIndex = (pageNum - 1) * pageSize;
            // 如果起始索引超出列表范围，返回空列表
            if (startIndex >= allTorrents.size()) {
                startIndex = allTorrents.size();
                // 如果是超出范围的页码，返回空列表
                if (pageNum > 1 && startIndex == 0) {
                    allTorrents = new ArrayList<>();
                }
            }
            
            int endIndex = Math.min(startIndex + pageSize, allTorrents.size());
            List<Map<String, Object>> pagedTorrents = startIndex < endIndex ? 
                allTorrents.subList(startIndex, endIndex) : new ArrayList<>();
            
            // 构建响应
            Map<String, Object> result = new HashMap<>();
            result.put("batchId", batchId);
            result.put("torrents", pagedTorrents);
            result.put("total", allTorrents.size());
            
            // 添加分页信息
            int totalPages = (int) Math.ceil((double) allTorrents.size() / pageSize);
            result.put("totalPages", totalPages);
            result.put("currentPage", pageNum);
            result.put("pageSize", pageSize);
            
            return new ResponseEntity<>(Result.success(result, "获取热门种子成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取热门种子时发生错误: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("获取热门种子失败: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取所有符合条件的热门种子总数
     * @return 热门种子总数
     */
    private int getTotalHotTorrentsCount() {
        try {
            // 获取所有状态正常的种子
            List<TorrentFile> allTorrents = torrentFileService.getAllTorrentFiles().stream()
                .filter(t -> t.getStatus() == 1)
                .collect(Collectors.toList());
            
            log.debug("数据库中共有 {} 个状态正常的热门种子", allTorrents.size());
            
            return allTorrents.size();
        } catch (Exception e) {
            log.error("获取热门种子总数时发生错误: {}", e.getMessage(), e);
            return 0;
        }
    }

    @DeleteMapping("/delete/{tid}")
    public ResponseEntity<Map<String, Object>> deleteTorrentFile(
            @RequestHeader Map<String, String> header,
            @PathVariable int tid) {

        Map<String, Object> response = new HashMap<>();
        DecodedJWT decodedJWT;
        String token = header.get("token");
        
        // 如果没有找到token头，尝试从Authorization头获取
        if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
            String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
            // 检查是否包含Bearer前缀
            if (authHeader != null && !authHeader.isEmpty()) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7); // 移除"Bearer "前缀
                } else {
                    token = authHeader;
                }
                System.out.println("从Authorization头提取token: " + token);
            }
        }
        
        if (token == null || token.isEmpty()) {
            response.put("success", false);
            response.put("message", "未提供有效的认证信息");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        try {
            decodedJWT = JWTUtil.verifyToken(token);
            int uid = decodedJWT.getClaim("uid").asInt();
            int usertype = decodedJWT.getClaim("usertype").asInt(); // 获取用户类型（0=管理员，1=普通用户）

            // 校验用户权限：仅允许文件所有者或管理员删除
            Optional<TorrentFile> optionalFile = torrentFileService.getTorrentFileByTid(tid);
            if (!optionalFile.isPresent()) {
                response.put("success", false);
                response.put("message", "种子文件不存在");
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }

            TorrentFile file = optionalFile.get();
            boolean isOwner = file.getUid() == uid;
            boolean isAdmin = usertype == 0;

            if (!isOwner && !isAdmin) {
                response.put("success", false);
                response.put("message", "无权限删除此文件");
                return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
            }

            // 删除物理文件
            String filePath = ROOT_PATH + File.separator + file.getFileUrl();
            File physicalFile = new File(filePath);
            if (physicalFile.exists() && !physicalFile.delete()) {
                response.put("success", false);
                response.put("message", "删除物理文件失败");
                return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
            }

            // 删除数据库记录
           torrentFileService.deleteTorrentFile(tid);

            response.put("success", true);
            response.put("message", "种子文件删除成功");
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (Exception e) {
            log.error("删除种子文件失败: {}", e.getMessage());
            response.put("success", false);
            response.put("message", "删除失败，请重试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取筛选和排序后的种子列表
     * @param type 筛选类型：0=全部种子，1=仅活种（做种人数>=1）
     * @param orderColumn 排序字段：1=上传时间，2=文件大小，3=点击数，4=下载数
     * @param orderType 排序方式：1=倒序，2=正序
     * @param sale 促销筛选：1=不筛选，2=30%折扣，3=50%折扣，4=免费
     * @return 筛选排序后的种子列表
     */
    @GetMapping("/filter")
    public ResponseEntity<?> getFilteredTorrents(
            @RequestParam(defaultValue = "0") String type,
            @RequestParam(defaultValue = "1") Integer orderColumn,
            @RequestParam(defaultValue = "1") Integer orderType,
            @RequestParam(defaultValue = "1") Integer sale) {
        
        try {
            // 获取所有种子文件
            List<TorrentFile> torrentFiles = torrentFileService.getAllTorrentFiles();
            
            // 计算所有状态为1的种子总数
            long totalAvailableTorrents = torrentFiles.stream()
                .filter(t -> t.getStatus() == 1)
                .count();
            
            List<TorrentFile> filteredFiles = new ArrayList<>();

            int type2 = Integer.parseInt(type);
            
            // 筛选活种（如果需要）
            if (type2 == 1) { // 仅活种
                for (TorrentFile file : torrentFiles) {
                    // 获取种子对应的InfoHash
                    String infoHash = torrentFileService.getInfoHashByTid(file.getTid());
                    if (infoHash != null) {
                        // 查询做种信息
                        TorrentSeedStats stats = torrentSeedStatsService.getStatsByInfoHash(infoHash);
                        // 只保留做种人数 >= 1 的种子
                        if (stats != null && stats.getSeeders() != null && stats.getSeeders() >= 1) {
                            filteredFiles.add(file);
                        }
                    }
                }
            } else { // 全部种子
                filteredFiles.addAll(torrentFiles);
            }
            
            // 促销筛选
            if (sale > 1) { // 1=不筛选，2=30%，3=50%，4=免费
                List<TorrentFile> saleFiltered = new ArrayList<>();
                for (TorrentFile file : filteredFiles) {
                    // 获取促销信息
                    Map<String, Object> discountInfo = promotionService.getMaxDiscountInfo(file.getTid());
                    String discountName = (String) discountInfo.get("discountName");
                    
                    // 根据促销类型筛选
                    if (sale == 2 && discountName.equals("30%折扣")) {
                        saleFiltered.add(file);
                    } else if (sale == 3 && discountName.equals("50%折扣")) {
                        saleFiltered.add(file);
                    } else if (sale == 4 && discountName.equals("免费")) {
                        saleFiltered.add(file);
                    }
                }
                filteredFiles = saleFiltered;
            }
            
            // 排序处理
            switch (orderColumn) {
                case 1: // 上传时间
                    if (orderType == 1) { // 倒序
                        filteredFiles.sort((a, b) -> b.getUploadTime().compareTo(a.getUploadTime()));
                    } else { // 正序
                        filteredFiles.sort((a, b) -> a.getUploadTime().compareTo(b.getUploadTime()));
                    }
                    break;
                case 2: // 文件大小
                    if (orderType == 1) { // 倒序
                        filteredFiles.sort((a, b) -> b.getFileSize().compareTo(a.getFileSize()));
                    } else { // 正序
                        filteredFiles.sort((a, b) -> a.getFileSize().compareTo(b.getFileSize()));
                    }
                    break;
                case 3: // 点击数
                    if (orderType == 1) { // 倒序
                        filteredFiles.sort((a, b) -> b.getViewCount() - a.getViewCount());
                    } else { // 正序
                        filteredFiles.sort((a, b) -> a.getViewCount() - b.getViewCount());
                    }
                    break;
                case 4: // 下载数
                    if (orderType == 1) { // 倒序
                        filteredFiles.sort((a, b) -> b.getDownloadCount() - a.getDownloadCount());
                    } else { // 正序
                        filteredFiles.sort((a, b) -> a.getDownloadCount() - b.getDownloadCount());
                    }
                    break;
                default:
                    // 默认按上传时间倒序
                    filteredFiles.sort((a, b) -> b.getUploadTime().compareTo(a.getUploadTime()));
            }
            
            // 将结果转换为前端需要的格式
            List<Map<String, Object>> result = new ArrayList<>();
            for (TorrentFile file : filteredFiles) {
                Map<String, Object> data = new HashMap<>();
                data.put("tid", file.getTid());
                data.put("title", file.getTitle());
                data.put("fileUrl", file.getFileUrl());
                data.put("fileSize", file.getFileSize());
                data.put("uploadTime", file.getUploadTime());
                data.put("downloadCount", file.getDownloadCount());
                data.put("viewCount", file.getViewCount());
                data.put("category", Category.getNameByValue(file.getCategory()));
                data.put("status", file.getStatus());
                
                // 获取做种信息
                String infoHash = torrentFileService.getInfoHashByTid(file.getTid());
                if (infoHash != null) {
                    TorrentSeedStats stats = torrentSeedStatsService.getStatsByInfoHash(infoHash);
                    if (stats != null) {
                        data.put("seeders", stats.getSeeders());
                        data.put("leechers", stats.getLeechers());
                    } else {
                        data.put("seeders", 0);
                        data.put("leechers", 0);
                    }
                } else {
                    data.put("seeders", 0);
                    data.put("leechers", 0);
                }
                
                // 获取促销信息
                Map<String, Object> discountInfo = promotionService.getMaxDiscountInfo(file.getTid());
                data.put("promotion", discountInfo);
                
                result.add(data);
            }
            
            // 创建包含结果和总数的响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("torrents", result);
            response.put("total", filteredFiles.size()); // 筛选后的种子数量
            response.put("totalAvailable", totalAvailableTorrents); // 所有状态为1的种子总数
            
            return ResponseEntity.ok(Result.success(response, "获取筛选种子列表成功"));
        } catch (Exception e) {
            log.error("筛选种子列表失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Result.fail("筛选种子列表失败: " + e.getMessage()));
        }
    }

}